<?php

namespace app\controller;

use app\BaseController;
use app\common\JwtTool;
use app\model\User;
use app\Request;

//  登录接口
class AuthController extends BaseController{
    public function login(Request $request){
        $data = $request->param();
        $user = new User();
        $user = $user->where('name',$data['name'])
            ->where('status',1)
            ->find();

        if(!$user)
            return json([
                'code' => 404,
                'msg' => '用户不存在或不可用'
            ],404);

        if (!password_verify($data['password'], $user->password)) {
            return json([
                'code' => 400,
                'msg' => '密码错误'
            ],400);
        }

        $payload = [
            'id' => $user->id,
            'name' => $user->name,
            'exp' => time() + 604800,  //  token过期时间(一周)
            'iat' => time(),        //  签发时间
            'iss' => 'eleming'      //  签发者
        ];

        $token = JwtTool::encode($payload);

        return json([
            'code' => 200,
            'msg' => '登录成功',
            'data' => [
                'token' => $token,
                'user' => [
                    'id' => $user->id,
                    'name' => $user->name,
                    'ip' => $request->ip()
                ]
            ]
        ]);
    }
}